/*
 * @Author: jiu yin
 * @Date: 2024-06-21 10:21:09
 * @LastEditTime: 2024-07-09 10:43:53
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \studio-web-admin\src\view\map_management\component\CodeTable.tsx
 * jiu
 */
import { list_online_device_map, deploy_map_result } from "@/api/home";
import pico from "@/assets/image/pico.png";
import PicoStatus from "@/comment/PicoStatus";
import { CheckCircleTwoTone, CloseCircleTwoTone, LoginOutlined, SyncOutlined } from "@ant-design/icons";
import type { ActionType } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import { ConfigProvider, message } from "antd";
import { socket } from "@/utils/webSocket";
import EventBus from "@/utils/eventBus";
import { deviceStatus } from "@/enum";

import { useEffect, useRef, useState } from "react";
// import Deploy from "./Deploy";

export default function CodeTable(propr: any) {
	const { map_id, detail, setListPico } = propr;
	const actionRef = useRef<ActionType>(null);

	let [isOk, setIsOk] = useState(false);
	let [listData, setListData] = useState<any[]>([]);

	//进入就询问状态
	useEffect(() => {
		if (!isOk) return; //防止重复渲染
		custom_message();
	}, [isOk]);

	//询问状态
	function custom_message() {
		listData.forEach((item: any) => {
			if (item.deploy_version && detail.package_name && item.device_real_sn) {
				let params = {
					action: "device/custom/message",
					payload: {
						sn: item.device_real_sn, //逗号隔开
						body: JSON.stringify({
							cmd: "upgradeStatus",
							data: {
								package: detail.package_name,
								version: item.deploy_version,
								type: "zip",
							},
						}),
					},
				};
				try {
					if (!socket) return;
					socket.send(JSON.stringify(params));
				} catch (e) {}
			} else {
				console.count("询问数据不足");
			}
		});
	}

	//发送-------webSocket common页接受部署状态  CodeTable页定时器去扫更新
	const send = async (sn: string) => {
		if (detail.package_name && detail.file_url && detail.version) {
			let params = {
				action: "device/app/upgrade",
				payload: {
					package: detail.package_name,
					type: "zip",
					url: detail.file_url,
					version: detail.version,
					range: sn, //全部||单个
				},
			};
			socket.send(JSON.stringify(params));
			message.success("部署开始发起");
			//手动刷一条准备部署状态
			await deploy_map_result({
				package: detail.package_name,
				device_real_sn: sn,
				status: "draw_up",
				version: detail.version,
			});
			reload();
		} else {
			console.count("部署数据不足");
			console.log(
				"detail.version:" +
					detail.version +
					"/detail.package_name:" +
					detail.package_name +
					"detail.file_url:" +
					detail.file_url
			);
			message.error("部署数据不足");
		}
	};

	const columns = [
		{
			dataIndex: "index",
			valueType: "indexBorder",
			width: 100,
			align: "center",
		},
		{
			title: "设备信息",
			dataIndex: "char_name",
			hideInSearch: true,

			render: (_: any, item: any) => (
				<div className="flex items-center">
					<img src={pico} alt="" className="w-72px h-72px mr-10px" />

					<div className="text-align-left">
						<p className="c-#161940 text-14px font-700">{item.device_name}</p>
						<p className="c-#5B5B5B text-12px">SN：{item.device_real_sn}</p>
					</div>
				</div>
			),
		},
		{
			title: "设备状态",
			dataIndex: "visualize_gender",
			hideInSearch: true,
			align: "center",
			render: (_: any, item: any) => <PicoStatus status={item.status}></PicoStatus>,
		},
		{
			title: "已安装版本",
			dataIndex: "visualize_gender",
			hideInSearch: true,
			align: "center",
			render: (_: any, item: any) => <span>{item.version || "未安装"}</span>,
		},
		{
			title: "部署状态",
			dataIndex: "deploy_status",
			hideInSearch: true,
			align: "center",
			render: (_: any, item: any) => deploy_status(item.application_deploy_status),
		},
		{
			title: "操作",
			valueType: "option",
			key: "option",
			render: (_: any, item: any) => [
				<a
					key="editable"
					onClick={async () => {
						// 1当前空闲 2使用中
						if ([1, 2].includes(item.status)) {
							send(item.device_real_sn);
						} else {
							let find = deviceStatus.find((i: any) => i.status === item.status);
							message.error(`设备状态${find.label}, 无法部署`);
						}
					}}>
					部署
				</a>,
			],
		},
	];

	let deploy_status = (status: string) => {
		switch (status) {
			case "draw_up":
				return (
					<p className="c-#161940 text-14px">
						<SyncOutlined spin style={{ color: "#5864FF" }} /> &nbsp;准备开始部署
					</p>
				);
			case "down":
				return (
					<p className="c-#161940 text-14px">
						<SyncOutlined spin style={{ color: "#5864FF" }} /> &nbsp;开始下载
					</p>
				);
			case "fail":
				return (
					<p className="c-#161940 text-14px">
						<CloseCircleTwoTone twoToneColor="#FF606B" /> &nbsp;安装失败
					</p>
				);
			case "install":
				return (
					<p className="c-#161940 text-14px">
						<SyncOutlined twoToneColor="#f50" /> &nbsp;开始安装
					</p>
				);
			case "success":
				return (
					<p className="c-#161940 text-14px">
						<CheckCircleTwoTone twoToneColor="#52c41a" /> &nbsp;已部署
					</p>
				);

			default:
				return (
					<p className="c-#161940 text-14px">
						<LoginOutlined /> &nbsp;等待部署
					</p>
				);
		}
	};

	const reload = () => {
		actionRef.current && actionRef.current.reload();
	};

	useEffect(() => {
		EventBus.on("updateStatus_map", reload);
		return () => {
			EventBus.off("updateStatus_map", reload);
		};
	}, []);

	return (
		<section className="mt-40px">
			<h3 className="c-#161940 text-20px">设备部署情况</h3>
			<div className="mt-20px ml--24px">
				<ConfigProvider>
					<ProTable
						columns={columns}
						actionRef={actionRef}
						request={async (params, sort, filter) => {
							let { data } = await list_online_device_map({
								page: params.current,
								limit: params.pageSize,
								map_id,
							});
							data.data.forEach((item: any, index: number) => (item.key = index + 1));
							setListData(data.data);
							setListPico(data.data);
							if (!isOk) setIsOk(true); // 防止重复渲染
							return {
								data: data.data,
								success: true,
								total: data.total,
							};
						}}
						rowKey="key"
						search={false}
						options={false}
						pagination={{
							pageSize: 10,
							hideOnSinglePage: true,
						}}
						dateFormatter="string"
					/>
				</ConfigProvider>
			</div>
		</section>
	);
}
